package com.kly.springbootinit.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kly.springbootinit.annotation.AuthCheck;
import com.kly.springbootinit.common.BaseResponse;
import com.kly.springbootinit.common.DeleteRequest;
import com.kly.springbootinit.common.ErrorCode;
import com.kly.springbootinit.common.ResultUtils;
import com.kly.springbootinit.constant.UserConstant;
import com.kly.springbootinit.exception.BusinessException;
import com.kly.springbootinit.exception.ThrowUtils;
import com.kly.springbootinit.model.dto.exam.ExamAddRequest;
import com.kly.springbootinit.model.dto.exam.ExamEditRequest;
import com.kly.springbootinit.model.dto.exam.ExamQueryRequest;
import com.kly.springbootinit.model.dto.exam.ExamUpdateRequest;
import com.kly.springbootinit.model.entity.Exam;
import com.kly.springbootinit.model.entity.User;
import com.kly.springbootinit.model.vo.ExamVO;
import com.kly.springbootinit.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 考试接口
 *
 * @author <a href="https://github.com/likly">程序员鹿七</a>
 * @from <a href="https://www.code-nav.cn">编程导航学习圈</a>
 */
@RestController
@RequestMapping("/exam")
@Slf4j
public class ExamController {

    @Resource
    private ExamService examService;

    @Resource
    private UserService userService;

    // region 增删改查

    /**
     * 创建考试
     *
     * @param examAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addExam(@RequestBody ExamAddRequest examAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(examAddRequest == null, ErrorCode.PARAMS_ERROR);
        // todo 在此处将实体类和 DTO 进行转换
        Exam exam = new Exam();
        BeanUtils.copyProperties(examAddRequest, exam);
        // 数据校验
        examService.validExam(exam, true);
        // todo 填充默认值
        User loginUser = userService.getLoginUser(request);
        exam.setUserId(loginUser.getId());
        // 写入数据库
        boolean result = examService.save(exam);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        // 返回新写入的数据 id
        long newExamId = exam.getId();
        return ResultUtils.success(newExamId);
    }

    /**
     * 删除考试
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteExam(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Exam oldExam = examService.getById(id);
        ThrowUtils.throwIf(oldExam == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldExam.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = examService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 更新考试（仅管理员可用）
     *
     * @param examUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateExam(@RequestBody ExamUpdateRequest examUpdateRequest) {
        if (examUpdateRequest == null || examUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 在此处将实体类和 DTO 进行转换
        Exam exam = new Exam();
        BeanUtils.copyProperties(examUpdateRequest, exam);
        // 数据校验
        examService.validExam(exam, false);
        // 判断是否存在
        long id = examUpdateRequest.getId();
        Exam oldExam = examService.getById(id);
        ThrowUtils.throwIf(oldExam == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = examService.updateById(exam);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取考试（封装类）
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<ExamVO> getExamVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Exam exam = examService.getById(id);
        ThrowUtils.throwIf(exam == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return ResultUtils.success(examService.getExamVO(exam, request));
    }

    /**
     * 分页获取考试列表（仅管理员可用）
     *
     * @param examQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Exam>> listExamByPage(@RequestBody ExamQueryRequest examQueryRequest) {
        long current = examQueryRequest.getCurrent();
        long size = examQueryRequest.getPageSize();
        // 查询数据库
        Page<Exam> examPage = examService.page(new Page<>(current, size),
                examService.getQueryWrapper(examQueryRequest));
        return ResultUtils.success(examPage);
    }

    /**
     * 分页获取考试列表（封装类）
     *
     * @param examQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<ExamVO>> listExamVOByPage(@RequestBody ExamQueryRequest examQueryRequest,
                                                               HttpServletRequest request) {
        long current = examQueryRequest.getCurrent();
        long size = examQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<Exam> examPage = examService.page(new Page<>(current, size),
                examService.getQueryWrapper(examQueryRequest));
        // 获取封装类
        return ResultUtils.success(examService.getExamVOPage(examPage, request));
    }

    /**
     * 分页获取当前登录用户创建的考试列表
     *
     * @param examQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<ExamVO>> listMyExamVOByPage(@RequestBody ExamQueryRequest examQueryRequest,
                                                                 HttpServletRequest request) {
        ThrowUtils.throwIf(examQueryRequest == null, ErrorCode.PARAMS_ERROR);
        // 补充查询条件，只查询当前登录用户的数据
        User loginUser = userService.getLoginUser(request);
        examQueryRequest.setUserId(loginUser.getId());
        long current = examQueryRequest.getCurrent();
        long size = examQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<Exam> examPage = examService.page(new Page<>(current, size),
                examService.getQueryWrapper(examQueryRequest));
        // 获取封装类
        return ResultUtils.success(examService.getExamVOPage(examPage, request));
    }

    /**
     * 编辑考试（给用户使用）
     *
     * @param examEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editExam(@RequestBody ExamEditRequest examEditRequest, HttpServletRequest request) {
        if (examEditRequest == null || examEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 在此处将实体类和 DTO 进行转换
        Exam exam = new Exam();
        BeanUtils.copyProperties(examEditRequest, exam);
        // 数据校验
        examService.validExam(exam, false);
        User loginUser = userService.getLoginUser(request);
        // 判断是否存在
        long id = examEditRequest.getId();
        Exam oldExam = examService.getById(id);
        ThrowUtils.throwIf(oldExam == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldExam.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = examService.updateById(exam);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    // endregion
}
